package com.sangsang.ck.methods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.methods.SelectCount;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * ck 查看当前表未完成的mutation的数量
 *
 * @author liutangqi
 * @date 2023/12/26 10:53
 * @see SelectCount
 */
public class CkQueryMutationsCount extends AbstractMethod {
    /**
     * jdbc连接的URL
     */
    private String url;

    public CkQueryMutationsCount(String url) {
        this.url = url;
    }

    private static final String METHOD_NAME = "ckQueryMutationsCount";
    private static final String ORIGINAL_SQL = "<script>\n select count(1) from system.mutations where database= '%s' and table= '%s' and is_done =0; \n</script>";

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = String.format(ORIGINAL_SQL, this.getTableName(url), tableInfo.getTableName());
        SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addSelectMappedStatementForOther(mapperClass, METHOD_NAME, sqlSource, Integer.class);
    }

    /**
     * 通过数据库的连接信息获取表名
     *
     * @author liutangqi
     * @date 2023/12/26 11:02
     * @Param [url]
     **/
    private String getTableName(String url) {
        String substring = url.substring(0, url.indexOf("?"));
        return substring.substring(substring.lastIndexOf("/") + 1);
    }
}
